// Telnet demo:
// - Basic telnet socket handling using the TelnetInterface
// - Handling client's screen size
// - Handling socket being closed by client
// - Handling cleanly closing the socket by hand

import net from 'node:net'

import {Root} from 'tui-lib/ui/primitives'

import {TelnetInterface} from 'tui-lib/util/interfaces'

import AppElement from './basic-app.js'

const server = new net.Server(socket => {
  const telnetInterface = new TelnetInterface(socket)

  telnetInterface.getScreenSize().then(size => {
    const root = new Root(telnetInterface)
    root.w = size.width
    root.h = size.height

    telnetInterface.on('resize', newSize => {
      root.w = newSize.width
      root.h = newSize.height
      root.fixAllLayout()
    })

    const appElement = new AppElement()
    root.addChild(appElement)
    root.select(appElement)

    let closed = false

    appElement.on('quitRequested', () => {
      if (!closed) {
        telnetInterface.cleanTelnetOptions()
        socket.write('Goodbye!\n')
        socket.end()
        clearInterval(interval)
        closed = true
      }
    })

    socket.on('close', () => {
      if (!closed) {
        clearInterval(interval)
        closed = true
      }
    })

    const interval = setInterval(() => root.render(), 100)
  }).catch(error => {
    console.error(error)
    process.exit(1)
  })
})

server.listen(8008)
